<template>
  <div class="container">
    <div class="left-card"   >
      <LeftCard
      :transformed-data.sync="transformedData1"
       @update:transformedData="transformedData1 = $event"   @deletedGrouup="handleDeletedGrouup"></LeftCard>
    </div>
    <div class="edit-exam-container">
      <!-- 试卷基本信息 -->
      <el-card class="exam-card">
        <template #header>
          <div class="card-header">
            <h2 class="exam-title">编辑试卷: {{ exam.paperName }}</h2>
            <div class="exam-meta">
              <span class="exam-id">试卷ID: {{ exam.id }}</span>
              <span class="last-modified">最后修改时间: {{ formatDate(exam.date) }}</span>
            </div>
          </div>
        </template>

        <el-form :model="exam" label-width="120px" size="default">
          <el-form-item label="试卷名称">
            <el-input v-model="exam.paperName" placeholder="请输入试卷名称" />
          </el-form-item>
          <el-form-item label="考试时长">
            <el-input-number v-model="exam.paperDuration" :min="30" :max="240" :step="10" controls-position="right" />
            <span class="duration-unit">分钟</span>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 题目组管理 -->
      <el-card class="questions-card">
        <template #header>
          <div class="card-header">
            <h3>题目管理</h3>
            <el-dropdown @command="addQuestionGroup">
              <el-button type="primary" plain>
                <el-icon>
                  <plus />
                </el-icon>添加题目组
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="(label, key) in QUESTION_TYPES" :key="key" :command="key">
                    {{ label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>

        <!-- 题目组列表 -->
        <div v-if="!exam.questionGroupList.length" class="empty-state">
          <el-empty description="暂无题目组，请先添加题目组" />
        </div>
        <div style="width: 100%; display: flex; flex-direction: column; justify-content: center;">
          <el-collapse v-model="activeGroups" accordion>
            <el-collapse-item v-for="(group, index) in exam.questionGroupList" :key="index" :name="index" >
              <template #title>
                <div class="group-header">
                  <div class="group-info">
                    <el-tag :type="getGroupTagType(group.quTypeDictText)" effect="plain">
                      {{ group.quTypeDictText }}
                    </el-tag>

                    <span class="question-count">{{ !group.quList || group.quList.length === 0 ? 1 : group.quList.length  }}题</span>
                  </div>

                  <div class="group-actions">
                    <el-button type="primary" text @click.stop="openQuestionBank(group)">
                      题库选题
                    </el-button>
                    <el-button type="danger" text @click.stop="removeQuestionGroup(index)">
                      删除组
                    </el-button>
                  </div>
                </div>
              </template>

              <!-- 题目列表 -->
              <div class="question-list">
                <div v-if="!group.quList || group.quList.length === 0 ? 1 : !group.quList.length " class="empty-state">
                  <el-empty description="暂无题目，请添加题目" />
                </div>

                <el-collapse >
                  <TransitionGroup name="list" tag="div" class="list-container">
                  <el-collapse-item v-for="(question, qIndex) in group.quList" :key="qIndex" :name="qIndex"
                    style="position: relative; ">
                    <template #title>
                      <div class="question-header">
                        <span class="question-index">第{{ qIndex + 1 }}题</span>

                        <!-- <el-tag
                      v-if="question.difficulty"
                      :type="getDifficultyTag(question.difficulty)"
                      size="small"
                    >
                      {{ question.difficulty }}
                    </el-tag> -->

                      </div>
                      <div style="position: absolute; left: 60px;display: flex; align-items: center;">
                        <el-icon @click="removeQuestion(group, questionIndex)" style="font-size: 18px;">
                          <DeleteFilled color="rgb(246, 79, 79)" />
                        </el-icon>
                        <div style="display: flex; gap: 15px; padding: 20px;">
                          <!-- 上箭头圆形 -->
                          <div style=" width: 20px; height: 20px;border-radius: 50%;background: #4CAF50;display: flex;align-items: center;justify-content: center; box-shadow: 0 4px 6px rgba(0,0,0,0.1);z-index: 1;" @click.stop="moveItem(qIndex, -1,index)">
                            <el-icon style="color: white; font-size: 14px;">
                              <Top />
                            </el-icon>
                          </div>

                          <!-- 下箭头圆形 -->
                          <div style="width: 20px;height: 20px;border-radius: 50%;background: #FF5722;display: flex;align-items: center;justify-content: center;box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 1;" @click.stop="moveItem(qIndex, 1,index)">
                            <el-icon style="color: white; font-size: 14px;">
                              <Bottom />
                            </el-icon>
                          </div>
                          </div>
                      <div  style="z-index: 1;">
                          <label >本题 &nbsp;</label>
                          <el-input-number  @click.stop  v-model="question.score" :min="0" :max="10" size="small" />
                          <label>&nbsp; 分</label>
                      </div>
                      </div>
                    </template>
                    <div style=" width: 100%; padding: 10px; padding-top: 0px; border-bottom: 2px solid  salmon;">
                      <div style="width: 100%;">
                        <Single :question="question" v-if="question.quType == 1" />
                        <Multipe v-if="question.quType == 2" :question="question"></Multipe>
                        <ShortAnswer v-if="question.quType == 4" :question="question"></ShortAnswer>
                        <Judgment v-if="question.quType == 3" :question="question"></Judgment>
                        <FillBank v-if="question.quType == 5" :question="question"></FillBank>
                      </div>



                    </div>


                  </el-collapse-item>
                </TransitionGroup>
                </el-collapse>

                <!-- <div class="add-question">
              <el-button type="primary" plain @click="addQuestion(group)">
                <el-icon><plus /></el-icon>添加题目
              </el-button>
            </div> -->
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>



      </el-card>




      <!-- 底部操作栏 -->
      <div class="action-bar">
        <el-button type="primary" size="large" @click="saveExam">
          <el-icon>
            <check />
          </el-icon>保存试卷
        </el-button>
        <el-button size="large" @click="cancel">取消</el-button>
      </div>

      <!-- 题库选择对话框 -->




      <!-- <div v-if="showQuestionBank" class="modal1" @click.self="closeModal">
      <div class="modal-content" role="dialog" aria-labelledby="userModalTitle">



      </div>
    </div> -->




    </div>

  </div>

  <div v-if="showQuestionBank" class="modal">
<div class="modal-content">
  <div class="modal-header">
    <h3>添加试题选择</h3>
    <button @click="showQuestionBank = false" class="close-button">
      <i class="fas fa-times"></i>
    </button>
  </div>
  <div style="overflow-y: auto; " v-if="showQuestionBank">
    <QuestionSelect @confirmQuestion="handleSelectQuestions" :quType="currentQuType"/>
  </div>
</div>
</div>


</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted,watch } from 'vue'
import { ElMessage, ElMessageBox,ElCard } from 'element-plus'
import { Check, Plus } from '@element-plus/icons-vue'
import QuestionEditor from './QuestionEditor.vue'
import { DeleteFilled, Top, Bottom } from '@element-plus/icons-vue'
import QuestionSelect from '@/components/exam/paper/QuestionSelect.vue'
import Single from '@/components/exam/questionnModel/Single.vue'
import Multipe from '@/components/exam/questionnModel/Multipe.vue'
import Judgment from '@/components/exam/questionnModel/Judgment.vue'
import ShortAnswer from '@/components/exam/questionnModel/ShortAnswer.vue'
import FillBank from '@/components/exam/questionnModel/FillBank.vue'
import LeftCard from '@/components/exam/paper/LeftCard.vue'
import { useRoute } from 'vue-router'
import Dialog from '@/components/commont/Dialog.vue'
import { ExamService } from '@/api/exam'
import { Save } from 'lucide-vue-next'
const route=useRoute()
const QUESTION_TYPES = {
  single: '单选题',
  multiple: '多选题',
  truefalse: '判断题',
  shortAnswer: '简答题'
}
const num = ref(1);
const DIFFICULTY_COLORS = {
  easy: 'success',
  medium: 'warning',
  hard: 'danger'
}
const currentQuType=ref(1);
let isUnmounted = false;
// 响应式数据
const activeGroups = ref([])
const showQuestionBank = ref(false)
const currentGroup = ref(null)

const exam = reactive({
  id: Math.floor(Math.random() * (999999 - 1 + 1)) + 1,
  paperName: '2023年度数学期末考试',
  date: new Date(),
  paperDuration: 120,
  questionGroupList: [],
  score:0

})

const getQuType = (type) => {
  const typeColors = {
    single: 1,
    multiple: 2,
    truefalse: 3,
    shortAnswer: 4
  }
  return typeColors[type] || 1
}

// 方法
const addQuestionGroup = (type) => {
  exam.questionGroupList.push({
    type:getGroupType(type),
    title:"",
    quList: [],
    quType:getQuType(type)
  })
  activeGroups.value = [exam.questionGroupList.length - 1]
}






const transformedData1 = computed({
  get() {
    return exam.questionGroupList.map(item => ({
      title: item.type,
      score: exam.score,
      count: !item.quList || item.quList.length === 0 ? 1 : item.quList.length
    }));
  },
  set(newValue) {
    // 将修改后的数据反向同步到原始数据
    newValue.forEach((newItem, index) => {
      const originalGroup = exam.questionGroupList[index];
      if (originalGroup) {
        originalGroup.type = newItem.title; // 更新题型名称
        // 注意：score 和 count 是计算属性，无需手动更新
      }
    });
  }
});
const moveItem = (qIndex, direction,index) => {
  const targetIndex = qIndex + direction;
  if (targetIndex < 0 || targetIndex >= exam.questionGroupList[index].quList.length) return;

  // 使用 Vue 的响应式数组方法
  const arr = [...exam.questionGroupList[index].quList];
  [arr[qIndex], arr[targetIndex]] = [arr[targetIndex], arr[qIndex]];
  exam.questionGroupList[index].quList = arr;
}
const removeQuestionGroup = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除这个题目组吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    exam.questionGroupList.splice(index, 1)
    ElMessage.success('题目组删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const   handleDeletedGrouup=((index)=>{
  exam.questionGroupList.splice(index, 1)
})
const addQuestion = (group) => {
  const baseQuestion = {
    content: '',
    difficulty: 'medium',
    score: 5,
    ...(group.type === 'shortAnswer' ? { referenceAnswer: '' } : {
      options: group.type === 'truefalse' ? ['正确', '错误'] : ['', ''],
      correctAnswer: group.type === 'multiple' ? [] : ''
    })
  }

  group.quList.push(baseQuestion)
  group.activeQuestions = [group.quList.length - 1]
}

const removeQuestion = (group, index) => {
  group.quList.splice(index, 1)
  ElMessage.success('题目删除成功')
}

const openQuestionBank = (group,quType) => {
  currentGroup.value = group
  currentQuType.value=group.quType;
  showQuestionBank.value = true
}

const handleSelectQuestions = (quList) => {
  console.log("parrrrrrr", quList)
  const data=quList.map(obj => {
    return { ...obj, score:1}});
  currentGroup.value.quList.push(...data)
  showQuestionBank.value = false
}



const cancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消编辑吗？所有未保存的更改将会丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    ElMessage.info('已取消编辑')
  } catch {
    // 取消操作
  }
}


const loadPaper = async (id) => {
  try {
    const response = await ExamService.getPaperQuestion({ id: id });
    if (!isUnmounted) {
      Object.assign(exam, response.data);
    }
  } catch (error) {
    if (!isUnmounted) {
      ElMessage.error('加载试卷失败');
    }
  }
}

// 创建响应式的路由参数监听
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.id && newQuery.action === 'edit') {
      exam.questionGroupList = []; // 清空原有题目
      loadPaper(newQuery.id);
    }

    if(newQuery.action === 'add'){
      exam.paperName=newQuery.paperName
      exam.paperDuration=newQuery.time
      exam.score=newQuery.score
    }
  },
  { immediate: true } // 立即执行一次以处理初始参数
);


const saveData = (exam) => {
  const id = route.query.id;
  const action= route.query.action;
  console.log("id",id)
  console.log("action",action)
if(action=="edit"){

}
if(action=="add"){
  exam.score=calculateTotalScore(exam);
  // if(exam.score>newQuery.score){
  //  alert("分数大于设定分数");
  // }
  ExamService.savePaper(exam);
}

}

const saveExam = () => {
  ElMessage.success('试卷保存成功')
  console.log('保存的试卷数据:', exam)
  saveData(exam);

}


onUnmounted(() => {
  exam.questionGroupList = [];
  isUnmounted = true;
  // 如果有事件监听或其他副作用，这里需要移除
});
// 工具方法
const formatDate = (date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getGroupTagType = (type) => {
  const typeColors = {
    单选题: 'primary',
    多选题: 'success',
    判断题: 'warning',
    简答题: 'info'
  }
  return typeColors[type] || 'default'
}
const getGroupType = (type) => {
  const typeColors = {
    single: '单选题',
    multiple: '多选题',
    truefalse: '判断题',
    shortAnswer: '简答题'
  }
  return typeColors[type] || 'none'
}
const getDifficultyTag = (difficulty) => {
  return DIFFICULTY_COLORS[difficulty] || 'info'
}
// 计算总分
function calculateTotalScore(data) {
  let totalScore = 0;

  // 遍历 FatherList
  if (Array.isArray(exam.questionGroupList)) {
    exam.questionGroupList.forEach(fatherItem => {
      // 遍历 List
      if (Array.isArray(fatherItem.quList)) {
        fatherItem.quList.forEach(item => {
          // 累加 score，默认值为 0
          totalScore += item.score || 0;
        });
      }
    });
  }
  return totalScore;
}
</script>

<style lang="scss" scoped>

.container {
  display: flex;
  justify-content: center;
  min-width: 100%;
  gap: 20px;
  animation: flip-to-left 0.6s ease-in-out forwards; /* 使用 ease-in-out */
}
@keyframes flip-to-left {
  0% {
    transform: rotateY(-180deg);
    opacity: 0; /* 初始透明度 */
  }
  2% {
    opacity: 0.05;
    transform: rotateY(-172deg);
  }
  5% {
    opacity: 0.1;
    transform: rotateY(-160deg);
  }
  10% {
    opacity: 0.2;
    transform: rotateY(-145deg);
  }
  15% {
    opacity: 0.3;
    transform: rotateY(-130deg);
  }
  20% {
    opacity: 0.4;
    transform: rotateY(-114deg);
  }
  30% {
    opacity: 0.6;
    transform: rotateY(-90deg);
  }
  40% {
    opacity: 0.75;
    transform: rotateY(-60deg);
  }
  50% {
    opacity: 0.85;
    transform: rotateY(-30deg);
  }
  60% {
    opacity: 0.95;
    transform: rotateY(-10deg);
  }
  70% {
    opacity: 1;
    transform: rotateY(0deg);
  }
  80% {
    opacity: 1;
    transform: rotateY(5deg);
  }
  90% {
    opacity: 1;
    transform: rotateY(2deg);
  }
  100% {
    transform: rotateY(0);
    opacity: 1;
  }
}
.left-card{
width: 30%;
max-width: 260px;
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 100%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  transition: transform 0.3s ease-out;
 position: relative;

}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  position: sticky;
  width: 100%;
  top: -18px;

}

.close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: var(--primary-color);
}

.edit-exam-container {
width: 100%;
flex-grow: 2;
  margin-right: 10px;
  .exam-card {
    margin-bottom: 5px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .exam-title {
        font-size: 1.4rem;
        color: var(--el-color-primary);
      }
      .exam-meta {
        display: flex;
        gap: 16px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
    }

    .duration-unit {
      margin-left: 8px;
      color: var(--el-text-color-secondary);
    }
  }

  .questions-card {
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    width: 100%;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
    }

    .empty-state {
      padding: 40px 0;
    }

    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      padding-right: 16px;

      .group-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .question-count {
          color: var(--el-text-color-secondary);
        }
      }
    }

    .question-list {
      padding: 10px;
      background: var(--el-fill-color-light);
      max-width: 100%;

      :deep(.el-collapse-item__content) {
        padding: 0 !important;
        justify-content: center;
        display: flex;
        width: 100%;
        /* 移除内容区域的内边距 */
      }

      border-radius: 8px;

      .question-header {
        display: flex;
        align-items: center;
        justify-content: space-around;
        position: relative;
        gap: 0px;
        font-size: 14px;
        padding-left: 15px;

        .question-index {
          font-weight: 600;
        }
      }

      .add-question {
        margin-top: 10px;
        text-align: center;
      }
    }
  }

  .action-bar {
    margin-top: 32px;
    text-align: center;

    .el-button {
      padding: 12px 32px;
      border-radius: 8px;
    }
  }
}
.list-move {
  transition: transform 0.4s ease;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.4s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}
</style>
